//
//  BN_NoticeHelper.m
//  BabyNow
//
//  Created by 闫建刚 on 14-5-11.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_NoticeHelper.h"
#import "IMB_NetWorkJsonRespOperation.h"
#import "IMB_NetWorkAccessOperationWithFilesUpload.h"
#import "BN_UserInfo.h"
#import "BN_UserHelper.h"
#import "IMB_NetFileUploadHelper.h"

@interface BN_NoticeHelper()
{
    int pageNo_;        // 通知列表查询页数
    
    NSMutableArray *dataArr_;  // 数据集合
    
    // 文件上传任务
    IMB_NetWorkAccessOperationWithFilesUpload *uploadOperation_;
    
    // 上传进度回调处理
    UploadProcessingHandler uploadProcessingHandler_;
    
    /**
     *  文件上传帮助类
     */
    IMB_NetFileUploadHelper *fileUploadHelper_;
}

/**
 *  通知列表查询队列
 */
@property (nonatomic,strong) NSOperationQueue *queryNoticeListQueue;

/**
 *  通知详情查询队列
 */
@property (nonatomic,strong) NSOperationQueue *queryNoticeDetailQueue;

/**
 *  发布通知队列
 */
@property (nonatomic,strong) NSOperationQueue *postNoticeQueue;


/**
 *  根据页码查询通知编号
 *
 *  @param pageNo 页码
 */
- (void)queryNoticeListWithPageNo:(int)pageNo;

@end

@implementation BN_NoticeHelper

#pragma mark - Extend method

- (void)queryNoticeListWithPageNo:(int)pageNo{
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_LIST requestMethod:NET_REQUEST_GET paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kPageno:[NSString stringWithFormat:@"%d",pageNo]} completeHandler:^(id result, NSString *errorMessage) {
        if(result){
            if([result[kErrorCode] intValue] == 0){
                id info = result[kinfo];
                if([info isKindOfClass:[NSArray class]] && [info count] > 0){
                    pageNo_ = pageNo;
                    if (pageNo == 1) {
                        [dataArr_ removeAllObjects];
                    }
                    //update by jason yan 2014-07-03 target:modifiy value of the dict
                    //[dataArr_ addObjectsFromArray:info];
                    for (NSDictionary *dict in info) {
                        [dataArr_ addObject:[dict mutableCopy]];
                    }
                    self.queryNoticeListHandler(dataArr_,errorMessage);
                }else{
                    if(pageNo == 1){
                        self.queryNoticeListHandler(nil,NET_ERROR_MSG_FOR_NO_DATA);
                    }else{
                        self.queryNoticeListHandler(nil,NET_ERROR_MSG_FOR_NO_MORE_DATA);
                    }
                }
            }else{
                self.queryNoticeListHandler(nil,result[kErrorMessage]);
            }
        }else{
            self.queryNoticeListHandler(nil,errorMessage);
        }
    }];
    [self.queryNoticeListQueue addOperation:operation];
}

#pragma mark - Interface method

// 刷新通知列表
- (void)refreshNoticeList{
    
    if (!_queryNoticeListHandler) {
        NSAssert(_queryNoticeListHandler, @"通知列表查询处理器不存在");
        return;
    }else if(self.queryNoticeListQueue.operationCount > 0){
        self.queryNoticeListHandler(nil,nil);
        return;
    }
    
    [self queryNoticeListWithPageNo:1];
}

// 查询下一页通知列表
- (void)queryNextPageNoticeList{
    
    if (!_queryNoticeListHandler) {
        NSAssert(_queryNoticeListHandler, @"通知列表查询处理器不存在");
        return;
    }else if(self.queryNoticeListQueue.operationCount > 0){
        self.queryNoticeListHandler(nil,nil);
        return;
    }
    [self queryNoticeListWithPageNo:pageNo_ + 1];
}

// 根据编号查询通知详情
- (void) queryNoticeDetailWithId:(NSString *)noticeId
                 completeHandler:(DataHandleComplete)completeHandler{
    
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_DETAIL requestMethod:NET_REQUEST_GET paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kNotiId:noticeId} completeHandler:^(id result, NSString *errorMessage) {
        if (result) {
            if([result[kErrorCode]intValue] == 0){
                completeHandler(result[kinfo],errorMessage);
            }else{
                completeHandler(nil,result[kErrorMessage]);
            }
        }else{
            completeHandler(nil,errorMessage);
        }
    }];
    [self.queryNoticeDetailQueue addOperation:operation];
}

// 根据编号回复通知
- (void)replyNoticeWithId:(NSString *)noticeId
             replyContent:(NSString *)replyContent
          completeHandler:(DataHandleComplete)completeHandler{
 
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_REPLY requestMethod:NET_REQUEST_POST paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kNotiId:noticeId,kReplCont:replyContent} completeHandler:^(id result, NSString *errorMessage) {
        if (result) {
            if([result[kErrorCode]intValue] == 0){
                completeHandler(result[kInfo],result[kErrorMessage]);
            }else{
                completeHandler(nil,result[kErrorMessage]);
            }
        }else{
            completeHandler(nil,errorMessage);
        }
    }];
    
    [[[NSOperationQueue alloc]init] addOperation:operation];
}

// 发布通知新接口
- (void)newPostNoticeWithTitle:(NSString *)title
                       content:(NSString *)content
                   fileInfoArr:(NSArray *)fileInfoArr
               completeHandler:(DataHandleComplete)completehandler
       uploadProcessingHandler:(UploadProcessingHandler)uploadProcessHandler{
    // BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
#warning 测试用户编号
    NSString *userId = TEST_USER_ID_TEACHER_1;
    
    fileUploadHelper_ = [[IMB_NetFileUploadHelper alloc]initWithUrlStr:NEW_NET_IF_PUBLISH_NOTICE commonFormParamsDict:@{kUserId:userId,kContent:content} fileInfoArr:fileInfoArr completeHandler:completehandler uploadProcessingHandler:uploadProcessHandler];
}

// 发布通知
- (void)postNoticeWithSubject:(NSString *)subject
                      content:(NSString *)content
                  fileInfoArr:(NSArray *)fileInfoArr
              completeHandler:(DataHandleComplete)completehandler
      uploadProcessingHandler:(UploadProcessingHandler)uploadProcessHandler{
    
    uploadProcessingHandler_ = uploadProcessHandler;
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_POST requestMethod:NET_REQUEST_POST paramsValues:nil completeHandler:^(id result, NSString *errorMessage) {
        NSLog(@"发布通知结果：%@",result);
        if (errorMessage) {
            completehandler(nil,errorMessage);
        }else{
            if ([result[kErrorCode]intValue] == 0) {
                completehandler(result[kErrorMessage],errorMessage);
            }else{
                completehandler(nil,result[kErrorMessage]);
            }
        }
    }];
    
    if (fileInfoArr) {
        // 1. 执行文件上传操作
        uploadOperation_ = [[IMB_NetWorkAccessOperationWithFilesUpload alloc]initWithUploadUrlStr:NET_IF_DYNAMIC_PUBLISH_UPLOAD_FILE paramsValues:@{kAccount: userInfo.account} paramsFileName:UPLOAD_FILE_PARAM_NAME paramsFileData:fileInfoArr completeHandler:^(id result, NSString *errorMessage) {
            
            [uploadOperation_ removeObserver:self forKeyPath:@"progress"];
            
            if (errorMessage) {
                [self.postNoticeQueue cancelAllOperations];
                completehandler(nil,errorMessage);
            }else if(result){
                NSError *err;
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:&err];
                if (err) {
                    completehandler(nil,NET_ERROR_MSG_FOR_RESPONSE_JSON_DATA);
                }else{
                    NSLog(@"文件上传结果：%@",dict);
                    // 检查errorCode
                    if ([dict[kErrorCode]intValue] == 0) {
                        //handler(dict[kinfo],nil);
                        
                        NSMutableString *fileIdsStr = [NSMutableString string];
                        NSArray *infoArr = dict[kinfo];
                        for (NSDictionary *fileDict in infoArr) {
                            [fileIdsStr appendString:fileDict[kFileId]];
                            [fileIdsStr appendString:SEPERATOR_FOR_FILE_IDS];
                        }
                        NSLog(@"fileIds:%@",fileIdsStr);
                        NSLog(@"通知发布地址：%@",NET_IF_NOTICE_POST);
                        
                        if (subject) {
                            operation -> paramsDict_ = @{kAccount: userInfo.account,kPassword:userInfo.password,kNotiSubj:subject,kFileIds:fileIdsStr,kNotiCont:content};
                        }else{
                            operation -> paramsDict_ = @{kAccount: userInfo.account,kPassword:userInfo.password,kFileIds:fileIdsStr};
                        }
                        
                    }else{
                        completehandler(nil,dict[kErrorMessage]);
                    }
                }
            }
        }];
        
        [operation addDependency:uploadOperation_];
        
        // 添加观察者
        [uploadOperation_ addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:NULL];
        
        [self.postNoticeQueue addOperation:uploadOperation_];
        
    }else{ // 图片不存在则必须提交通知内容
        
        operation -> paramsDict_ = @{kAccount: userInfo.account,kPassword:userInfo.password,kNotiSubj:subject};
    }
    [self.postNoticeQueue addOperation:operation];
    
}

// 根据编号删除通知
- (void)removeNoticeWithId:(NSString *)noticeId completeHandler:(DataHandleComplete)completeHandler{
    
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_DELETE requestMethod:NET_REQUEST_GET paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kNotiId:noticeId} completeHandler:^(id result, NSString *errorMessage) {
        if (result) {
            if([result[kErrorCode]intValue] == 0){
                completeHandler(result[kInfo],result[kErrorMessage]);
            }else{
                completeHandler(nil,result[kErrorMessage]);
            }
        }else{
            completeHandler(nil,errorMessage);
        }
    }];
    
    [[[NSOperationQueue alloc]init] addOperation:operation];
}

// 根据编号赞通知
- (void)supportNoticeWithId:(NSString *)noticeId flg:(int)flg completeHandler:(DataHandleComplete)completeHandler{
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_SUPPORT requestMethod:NET_REQUEST_POST paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kNotiId:noticeId,kFlg:[NSString stringWithFormat:@"%d",flg]} completeHandler:^(id result, NSString *errorMessage) {
        if (result) {
            if([result[kErrorCode]intValue] == 0){
                completeHandler(result[kInfo],result[kErrorMessage]);
            }else{
                completeHandler(nil,result[kErrorMessage]);
            }
        }else{
            completeHandler(nil,errorMessage);
        }
    }];
    
    [[[NSOperationQueue alloc]init] addOperation:operation];
}

// 根据编号收藏通知
- (void)collectNoticeWithId:(NSString *)noticeId completeHandler:(DataHandleComplete)completeHandler{
    BN_UserInfo *userInfo = [BN_UserHelper unArchiverAccountInfo];
    
    IMB_NetWorkJsonRespOperation *operation = [[IMB_NetWorkJsonRespOperation alloc]initWithUrlStr:NET_IF_NOTICE_COLLECT requestMethod:NET_REQUEST_GET paramsValues:@{kAccount:userInfo.account,kPassword:userInfo.password,kNotiId:noticeId} completeHandler:^(id result, NSString *errorMessage) {
        if (result) {
            if([result[kErrorCode]intValue] == 0){
                completeHandler(result[kInfo],result[kErrorMessage]);
            }else{
                completeHandler(nil,result[kErrorMessage]);
            }
        }else{
            completeHandler(nil,errorMessage);
        }
    }];
    
    [[[NSOperationQueue alloc]init] addOperation:operation];
}


// 取消查询通知列表
- (void)cancelQueryNoticeList{
    [self.queryNoticeListQueue.operations makeObjectsPerformSelector:@selector(cancelNetAccess)];
}

// 取消查询通知详情
- (void)cancelQueryNoticeDetail{
    [self.queryNoticeDetailQueue.operations makeObjectsPerformSelector:@selector(cancelNetAccess)];
}

#pragma mark - Property method

- (NSOperationQueue*)queryNoticeListQueue{
    if (!_queryNoticeListQueue) {
        _queryNoticeListQueue = [[NSOperationQueue alloc]init];
    }
    return _queryNoticeListQueue;
}

- (NSOperationQueue*)queryNoticeDetailQueue{
    if (!_queryNoticeDetailQueue) {
        _queryNoticeDetailQueue = [[NSOperationQueue alloc]init];
    }
    return _queryNoticeDetailQueue;
}

- (NSOperationQueue*)postNoticeQueue{
    if (!_postNoticeQueue) {
        _postNoticeQueue = [[NSOperationQueue alloc]init];
    }
    return _postNoticeQueue;
}

#pragma mark - Life cycle method

- (void)dealloc{
    NSLog(@"BN_NoticeHelper dealloc ....");
}

- (id)init{
    if (self = [super init]) {
        dataArr_ = [NSMutableArray array];
    }
    return self;
}

// 观察者回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"progress"]) {
        IMB_NetWorkAccessOperationWithFilesUpload *operation = object;
        uploadProcessingHandler_(operation.progress);
    }
}

@end
